package com.blensmile.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.text.SpannableString;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.blensmile.BaseActivity;
import com.blensmile.R;
import com.blensmile.network.RestClient;
import com.blensmile.network.models.VoiceGradeBean;
import com.blensmile.utils.GetEncodeString;
import com.blensmile.utils.LogUtils;
import com.blensmile.utils.SysUtils;
import com.blensmile.utils.VoiceGrader;
import com.blensmile.view.BorderRoundImageView;
import com.blensmile.view.CircleImageView;
import com.google.gson.Gson;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Blensmile on 2017/3/16.
 */

public class UploadVoiceActivity extends BaseActivity {

    @BindView(R.id.tv_click)
    TextView tvClick;
    @BindView(R.id.tv_content)
    TextView tvContent;
    @BindView(R.id.civ_avatar)
    CircleImageView civAvatar;
    @BindView(R.id.img_avatar)
    BorderRoundImageView imgAvatar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_voice);
        ButterKnife.bind(this);
//        getdata();
    }

    private void encode() {
//        String str = getInnerSDCardPath() + "/encode";
//        LogUtils.b(str);
//        File file = new File(str + "/record.wav");
//        LogUtils.b("isExist " + file.exists());
//        LogUtils.b("isFile " + file.isFile());
//        File file1 = new File(str + "/encodeda");
//        try {
//            file1.createNewFile();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        char[] chars = GetEncodeString.getchars(str);
//        String string = String.valueOf(chars);
//        LogUtils.b("length:" + chars.length + "---contents:" + string);
//        tvContent.setText(string);
//        File f = new File(str + "/encodeda");
//
//        try {
//            BufferedWriter writer = new BufferedWriter(new FileWriter(f));
//            writer.write(string, 0, string.length());
//            writer.flush();
//            writer.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        postFile(str + "/encodedx");

        String path = getInnerSDCardPath() + "/encode";
        LogUtils.b(path);
        String input = path + "/record.wav";
        File infile = new File(input);
        LogUtils.b("isExist " + infile.exists());
        LogUtils.b("isFile " + infile.isFile());
//        tv.setText(str);
        String output = path + "/encodedx";
        long start = System.currentTimeMillis();
        boolean chars = GetEncodeString.getEncoded(input, output);
        LogUtils.b("time is: " + (System.currentTimeMillis() - start));
        String string = String.valueOf(chars);
        tvContent.setText(string);
        if (chars) {
            postFile("ENG-Basic-Level1-Unit1-Chapter1-A2-5-3", output);
        }

        VoiceGrader grader = new VoiceGrader(new VoiceGrader.GraderCallback() {
            @Override
            public void onErro() {

            }

            @Override
            public void onEncoded() {
            }

            @Override
            public void onGraded(VoiceGradeBean data) {
                tvContent.setText(data.toString());
            }
        });
        grader.execute("ENG-Basic-Level1-Unit1-Chapter1-A2-5-3", input, output);


    }

    public String getInnerSDCardPath() {
        return Environment.getExternalStorageDirectory().getPath();
    }

    private void getdata() {
        //http://api.200h.com/homework/lists?device_id=47bfe65b436e083e&verify=4b16a7e3f90155d221c056636f2e5e91&user_id=5819dc653a700e7c0b8b4569&page=0&ignore=0 (112ms)0
        String verify = "4b16a7e3f90155d221c056636f2e5e91";
        String userId = "5819dc653a700e7c0b8b4569";
        Call<Map<String, Object>> call = RestClient.getApiService().get_user_info(SysUtils.getDeviceId(), verify, userId);
        call.enqueue(new Callback<Map<String, Object>>() {
            @Override
            public void onResponse(Call<Map<String, Object>> call, Response<Map<String, Object>> response) {

            }

            @Override
            public void onFailure(Call<Map<String, Object>> call, Throwable t) {

            }
        });
    }

    private void postFile(final String code, final String path) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();
                String head = new String("http://10.0.1.217:3001/minos");
                RequestBody formbody = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("os", "android")
                        .addFormDataPart("formid", code)
                        .addFormDataPart("file", "file", RequestBody.create(MediaType.parse("application/octet-stream"), new File(path)))
                        .build();
                Request request = new Request.Builder()
                        .url(head)
                        .post(formbody)
                        .build();
                try {
                    okhttp3.Response response = client.newCall(request).execute();
                    String respon = response.body().string();
                    System.out.println(respon);
                    Gson gson = new Gson();
                    final VoiceGradeBean bean = gson.fromJson(respon, VoiceGradeBean.class);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tvContent.setText(bean.toString());
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    protected void onResume() {
        super.onResume();
//        showPrizeDialog();
    }

    private void showPrizeDialog() {

        final Dialog dialog = new Dialog(this, R.style.ActionSheetDialogStyle);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_learn_over_prize, null);
        View imgClose = view.findViewById(R.id.img_close);
        imgClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });
        View tvTry = view.findViewById(R.id.tv_try);
        tvTry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                    startActivity(new Intent(UploadVoiceActivity.this, BounceActivity.class));
                }

            }
        });

        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }


    int colors[] = {Color.TRANSPARENT, 0x80000000};
    int index1 = 0;
    int index2 = 0;

    @OnClick({R.id.civ_avatar, R.id.tv_click,R.id.img_avatar})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.civ_avatar:
//                civAvatar.setColorFilter(colors[index++ % 2]);
                civAvatar.setMaskingColor(colors[index1++ % 2]);
                break;
            case R.id.img_avatar:
                imgAvatar.setMaskingColor(colors[index2++ % 2]);
                break;
            case R.id.tv_click:
                encode();
                String s = "Text Text,sll 94:34; 32 32Text";
                String i = "bad  bad   good bad bad bad bad";
                i = i.toUpperCase();
                SpannableString string = VoiceGrader.getCorrected(s, i);
                if (string != null) {
                    tvClick.setText(string, TextView.BufferType.SPANNABLE);
                }
//                SysUtils.getCpuArch();
                break;
        }
    }

}
